using System;
using System.Collections.Generic;
using System.Text;
using System.Net.NetworkInformation;
using System.Net;
using System.Data;
namespace TestX {
	class TofPing {
		public static DAL local=new DAL();
		public static DAL dal=new DAL("pon-wpsq21-db08\\in08","rf");
		public static Ping p=new Ping();
		static void MainX() {
			//dal.NonQry("create table ping(id int identity,inserted datetime default getdate(),ip varchar(15),pval int,perr int)");
			//dal.NonQry("truncate table ping");
			//DataTable tab=dal.Query("SELECT * FROM TofBox(nolock)where dns like 'TOF%VX%' or dns like 'NEO%TOFWH%'");
			DataTable tab=dal.Query("select * from rfstate where lastUpdate>getdate()-1./12");
			List<string> ips=new List<string>();
			foreach(DataRow row in tab.Rows)
				//ips.Add(row["ip"].ToString());
				ips.Add(row["address"].ToString().Trim());
			Dictionary<string,int> invalid=new Dictionary<string,int>();
			for(int i=0;i<1;i++)
			{
				foreach(string ip in ips)
				{
					int roundtrip=1000;
					PingReply pr=p.Send(ip,roundtrip);
					if(pr.Status==IPStatus.Success)
						roundtrip=(int)pr.RoundtripTime;
					else
					{
						if(!invalid.ContainsKey(ip))
							invalid.Add(ip,1);
						else
							invalid[ip]++;
					}
				}
			}
			foreach(string strip in invalid.Keys)
				ips.Remove(strip);
			//int cnt=0;
			while(true)
			{
				//if(cnt++%5000==0) {
				//  DataTable rem=dal.Query("select ");
				//}
				ips.Remove("172.26.17.3");
				foreach(string ip in ips)
				{
					int roundtrip=1000;
					//System.Diagnostics.Stopwatch sw=System.Diagnostics.Stopwatch.StartNew();
					PingReply pr=new Ping().Send(ip,roundtrip);
					//long elapsed=sw.ElapsedMilliseconds;
					if(pr.Status==IPStatus.Success)
						roundtrip=(int)pr.RoundtripTime;
					else
					{
						Console.WriteLine(ip);
						//ips.Remove(ip);
						//break;

					}
					local.NonQry("insert into Ping with(rowlock)(ip,pval,perr)values('{0}',{1},{2})",ip,roundtrip,(int)pr.Status);
					//System.Threading.Thread.Sleep(100);
				}
			}
		}
		static void MainC() {
			DAL dal=new DAL();

			//dal.NonQry("drop table TofBox2");
			dal.NonQry("create table TofBox2(id int identity,ip varchar(15),dns varchar(255))");
			string ipbase="172.27.{0}.{1}";
			Ping p=new Ping();
			for(int j=16;j<=20;j++)
				for(int i=1;i<255;i++)
				{
					string ip=string.Format(ipbase,j,i);
					//PingReply rep=p.Send(ip,50);
					//if(rep.Status==IPStatus.Success)
					try
					{
						IPHostEntry ent=Dns.GetHostEntry(ip);
						if(ip!=ent.HostName)
						{
							dal.NonQry("insert into TofBox2(ip,dns)values('{0}','{1}')",ip,ent.HostName.Replace(".next-uk.next.loc",""));
							Console.WriteLine("{0},{1}",ip,ent.HostName);
						}
					}
					catch(Exception ex) { Console.WriteLine(ip+"-"+ex.Message); }
				}
		}
	}
}
